#include <Servo.h>

Servo myServo;

const int trigPin = 9;
const int echoPin = 10;
int angle = 0;

void setup() {
  Serial.begin(9600);           // 初始化串口通信
  myServo.attach(11);           // 舵机控制信号接 11 号引脚
  pinMode(trigPin, OUTPUT);     // 超声波 trig 为输出
  pinMode(echoPin, INPUT);      // 超声波 echo 为输入
}

void loop() {
  // 从 0° 转到 180°
  for (angle = 0; angle <= 180; angle++) {
    myServo.write(angle);
    delay(30);
    long duration, distance;

    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    duration = pulseIn(echoPin, HIGH);
    distance = duration * 0.034 / 2;  // 距离单位：cm

    Serial.print(angle);
    Serial.print(",");
    Serial.println(distance);
  }

  // 从 180° 转回 0°
  for (angle = 180; angle >= 0; angle--) {
    myServo.write(angle);
    delay(30);
    long duration, distance;

    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    duration = pulseIn(echoPin, HIGH);
    distance = duration * 0.034 / 2;

    Serial.print(angle);
    Serial.print(",");
    Serial.println(distance);
  }
}
